<template>
  <div>
    <div class="mlt">
      <el-button
        v-if="flag == 0"
        v-permissions="{ permission: ['add:TemplateSetting'] }"
        type="primary"
        @click="addRole"
      >
        添加模板
      </el-button>
      <el-button v-if="flag == 1" type="primary" @click="addRole">
        添加标题
      </el-button>
      <el-button v-if="flag == 1" type="primary" @click="updataPositions">
        返回
      </el-button>
      <el-button v-if="flag == 2" type="primary" @click="addAttribute">
        添加属性
      </el-button>
      <el-button v-if="flag == 2" type="primary" @click="returntmp">
        返回
      </el-button>
    </div>
    <div class="mlt">
      <!-- 模板列表 -->
      <el-table
        v-if="flag == 0"
        :data="tableData"
        :empty-text="emptyText"
        style="width: 100%"
      >
        <el-table-column label="模板名称" prop="group_name" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              v-permissions="{ permission: ['view:TemplateSetting'] }"
              size="mini"
              type="primary"
              @click="addTemplate(scope.row)"
            >
              查看
            </el-button>
            <el-button
              v-permissions="{ permission: ['edit:TemplateSetting'] }"
              size="mini"
              type="warning"
              @click="modifyTemplate(scope.row)"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- -------------------------------------------------------------------------- -->
      <!-- 标题列表 -->
      <el-table v-show="flag == 1" ref="table" :data="tableData1" row-key="id">
        <el-table-column label="标题" prop="type_name" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="addTitle(scope.row)">
              查看
            </el-button>
            <el-button
              size="mini"
              type="warning"
              @click="modifyTitle(scope.row)"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- -------------------------------------- -->
      <el-table v-show="flag == 2" ref="tables" :data="tableData2" row-key="id">
        <el-table-column label="字段名" prop="item_name" />
        <el-table-column label="输入类型" prop="data_type" />
        <el-table-column label="提醒内容" prop="data_scope" />
        <el-table-column label="输入值" prop="data_value" />
        <el-table-column label="单位" prop="data_unit" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              @click="modifyItem(scope.row)"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- --------------------------------- -->
    </div>
    <el-dialog
      :before-close="handleClose"
      title="添加类型"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <div v-if="flag == 0">
        <span>模板名称</span>
        <el-input
          v-model="group_name"
          placeholder="请输入模板名称 "
          style="width: 40%; margin-left: 10px"
        />
        <!-- <br />
        <span>模板分组</span>
        <el-select
          v-model="type_code"
          placeholder="请选择"
          style="width: 40%; margin-left: 10px; margin-top: 10px"
        >
          <el-option
            v-for="item in opList"
            :key="item.menu_key"
            :label="item.menu_name"
            :value="item.menu_key"
          />
        </el-select> -->
      </div>
      <div v-if="flag == 1">
        <span>标题名称</span>
        <el-input
          v-model="type_name"
          placeholder="请输入模板名称 "
          style="width: 40%; margin-left: 10px"
        />
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="SubmitClick">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :before-close="handleClose"
      title="添加类型"
      :visible.sync="dialogVisibles"
      width="70%"
    >
      <div>
        <el-form ref="form" label-width="80px" :model="itemForm">
          <el-form-item label="字段名">
            <el-input v-model="itemForm.item_name" placeholder="请输入字段名" />
          </el-form-item>
          <!-- <el-form-item label="键名">
            <el-input v-model="itemForm.users" placeholder="请输入键名" />
          </el-form-item> -->
          <el-form-item label="输入类型">
            <el-radio-group v-model="itemForm.data_type">
              <el-radio :label="'input_str_r'">只读输入框</el-radio>
              <el-radio :label="'input_str_w'">可写输入框</el-radio>
              <el-radio :label="'input_radio'">单选</el-radio>
              <el-radio :label="'input_checkbox'">复选</el-radio>
              <el-radio :label="'input_select'">下拉菜单</el-radio>
              <el-radio :label="'input_num_w'">数字类型</el-radio>
              <el-radio :label="'input_file'">文件上传</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="单位">
            <el-input v-model="itemForm.data_unit" placeholder="请输入单位" />
          </el-form-item>
          <el-form-item label="提醒内容">
            <div
              v-if="
                itemForm.data_type == 'input_str_w' ||
                itemForm.data_type == 'input_select' ||
                itemForm.data_type == 'input_num_w'
              "
            >
              <el-input
                v-model="itemForm.data_scope"
                placeholder="请输入提醒内容"
              />
            </div>
            <div
              v-if="
                itemForm.data_type == 'input_radio' ||
                itemForm.data_type == 'input_select' ||
                itemForm.data_type == 'input_checkbox'
              "
            >
              <el-tag
                v-for="(tag, index) in dynamicTags"
                :key="index"
                closable
                :disable-transitions="false"
                style="margin-left: 33px"
                @close="handleClose1(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="saveTagInput"
                v-model="inputValue"
                class="input-new-tag"
                size="small"
                style="width: 100px; margin-left: 33px"
                @blur="handleInputConfirm"
                @keyup.enter.native="handleInputConfirm"
              />
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                style="margin-left: 33px"
                @click="showInput"
              >
                + 添加可选项
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibles = false">取 消</el-button>
        <el-button type="primary" @click="SubmitAttributeClick">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- <div v-if="total != ''">
      <el-pagination background layout="prev, pager, next" :total="total" />
    </div> -->
  </div>
</template>

<script>
  import {
    reportGroupList,
    reportTypeList,
    reportAroupAdd,
    reportTypeAdd,
    reportTypeItemList,
    setReportTypeSort,
    reportTypeItemAdd,
    setReportItemSort,
    // reciveTreatmentMenu,
  } from '@/api/template'
  // import { getDepartmentList } from '@/api/addOrganization'
  import Sortable from 'sortablejs'
  export default {
    name: 'Reception',

    data() {
      return {
        type_id: '',
        titleId: '',
        group_name: '',
        // type_code: '',
        type_name: '',
        emptyText: ' ',
        tableData: [],
        tableData1: [],
        tableData2: [],
        departmentValue: '',
        departmentList: [],
        dialogVisible: false,
        dialogVisibles: false,
        //切换页面状态
        flag: 0,
        group_id: '',
        modifyTemId: '',
        itemForm: {
          item_name: '',
          data_type: '',
          data_scope: '',
          data_unit: '',
        },
        dynamicTags: [],
        inputVisible: false,
        inputValue: '',
        itemId: '',
        // opList: {},
      }
    },
    computed: {},
    watch: {},
    created() {},
    mounted() {
      this.init()
    },
    methods: {
      // 初始化
      init() {
        const loading = this.$loading({
          lock: true,
          target:
            this.tableData.length == 0
              ? '.el-table__empty-block'
              : '.el-table__body',
        })
        reportGroupList().then((res) => {
          this.tableData = res.data
          loading.close()
          if (res.data.length == 0) {
            this.emptyText = '暂无数据'
          }
        })
        // reciveTreatmentMenu().then((e) => {
        //   this.opList = e.data
        //   console.log(e)
        // })
      },
      // 新增模块
      addRole() {
        this.dialogVisible = true
        this.type_code = ''
        this.group_name = ''
      },
      addAttribute() {
        this.itemForm = {
          item_name: '',
          data_type: '',
          data_scope: '',
          data_unit: '',
        }
        this.dynamicTags = []
        this.dialogVisibles = true
      },
      // 新增模板 and 标题
      SubmitClick() {
        if (this.flag == 1) {
          const params = {
            group_id: this.group_id,
            type_name: this.type_name,
            id: this.titleId,
          }
          const jy = {
            type_name: '请输入标题名称',
          }

          if (Object.keys(params).length === 0) {
            this.$message.error('请填写信息')
            return
          } else {
            for (var key in params) {
              if (key == 'type_name') {
                if (params[key] == '') {
                  this.$message.error(jy[key])
                  return
                }
              }
            }
          }
          reportTypeAdd(params).then(() => {
            const params = {
              group_id: this.group_id,
            }
            reportTypeList(params).then((res) => {
              this.titleId = ''
              this.type_name = ''
              this.tableData1 = res.data
            })
          })
        } else {
          const params = {
            type_code: this.type_code,
            group_name: this.group_name,
            id: this.modifyTemId,
          }
          const jy = {
            group_name: '请输入模板名称',
            type_code: '请选择分组',
          }

          if (Object.keys(params).length === 0) {
            this.$message.error('请填写信息')
            return
          } else {
            for (var keys in params) {
              if (keys == 'group_name') {
                if (params[keys] == '') {
                  this.$message.error(jy[keys])
                  return
                }
              }
            }
          }
          reportAroupAdd(params).then(() => {
            this.modifyTemId = ''
            this.group_name = ''
            this.init()
          })
        }

        this.dialogVisible = false
      },
      SubmitAttributeClick() {
        if (
          this.itemForm.data_type == 'input_radio' ||
          this.itemForm.data_type == 'input_select' ||
          this.itemForm.data_type == 'input_checkbox'
        ) {
          this.itemForm.data_value = JSON.stringify(this.dynamicTags)
        } else {
          this.itemForm.data_value = ''
        }
        this.itemForm.type_id = this.type_id
        this.itemForm.group_id = this.group_id
        this.itemForm.id = this.itemId

        reportTypeItemAdd(this.itemForm).then(() => {
          const loading = this.$loading({
            lock: true,
            target:
              this.tableData1.length == 0
                ? '.el-table__empty-block'
                : '.el-table__body',
          })
          this.dialogVisibles = false
          const paramse = {
            group_id: this.group_id,
            type_id: this.type_id,
          }
          reportTypeItemList(paramse).then((e) => {
            this.tableData2 = e.data
            loading.close()
            this.itemId = ''
          })
        })
      },
      // 模板List
      addTemplate(e) {
        const loading = this.$loading({
          lock: true,
          target:
            this.tableData.length == 0
              ? '.el-table__empty-block'
              : '.el-table__body',
        })
        this.group_id = e.id
        const params = {
          group_id: this.group_id,
        }
        reportTypeList(params)
          .then((res) => {
            this.tableData1 = res.data
            this.flag = 1
            this.$message({
              type: 'success',
              message: '成功!',
            })
            this.setSort()
            loading.close()
          })
          .catch(() => {
            this.$message.error('失败')
          })
      },
      // 类型list
      addTitle(e) {
        const loading = this.$loading({
          lock: true,
          target:
            this.tableData1.length == 0
              ? '.el-table__empty-block'
              : '.el-table__body',
        })
        this.type_id = e.id
        const params = {
          group_id: e.group_id,
          type_id: e.id,
        }
        reportTypeItemList(params).then((e) => {
          this.tableData2 = e.data
          this.flag = 2
          this.setSorts()
          loading.close()
        })
      },
      // 修改模板
      modifyTemplate(e) {
        this.group_name = e.group_name
        this.modifyTemId = e.id
        this.dialogVisible = true
      },
      // 修改模板标题
      modifyTitle(e) {
        this.titleId = e.id
        this.type_name = e.type_name

        this.dialogVisible = true
      },
      // 修改属性
      modifyItem(e) {
        this.itemId = e.id
        this.itemForm = {
          item_name: e.item_name,
          data_type: e.data_type,
          data_scope: e.data_scope,
          data_unit: e.data_unit,
        }
        this.dynamicTags = e.data_value || []
        this.dialogVisibles = true
      },
      updataPositions() {
        this.flag = 0
      },
      returntmp() {
        this.flag = 1
      },

      // 关闭弹框的回调
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(() => {
            done()
            this.form = {}
          })
          .catch(() => {})
      },
      handleClose1(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      },

      showInput() {
        this.inputVisible = true
        this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },

      handleInputConfirm() {
        let inputValue = this.inputValue
        if (inputValue) {
          this.dynamicTags.push(inputValue)
        }
        this.inputVisible = false
        this.inputValue = ''
      },
      raionChange() {
        this.itemForm.data_unit = ''
        this.itemForm.data_scope = ''
        this.dynamicTags = []
      },
      // 表格的拖拽类型list
      setSort() {
        //ref一定跟table上面的ref一致
        const el = this.$refs.table.$el.querySelectorAll(
          '.el-table__body-wrapper > table > tbody'
        )[0]
        this.sortable = Sortable.create(el, {
          ghostClass: 'sortable-ghost',
          setData: function (dataTransfer) {
            dataTransfer.setData('Text', '')
          },
          // 监听拖拽事件结束时触发
          onEnd: (evt) => {
            // 拖动行的前一行
            const targetRow = this.tableData1.splice(evt.oldIndex, 1)[0]
            // 拖动行的后一行
            this.tableData1.splice(evt.newIndex, 0, targetRow)
            const arr = []
            this.tableData1.forEach((e, index) => {
              //
              arr.push({
                id: e.id,
                sort: index,
              })
            })
            const sortData = JSON.stringify(arr)
            const params = {
              group_id: this.group_id,
              sort_data: sortData,
            }
            setReportTypeSort(params).then(() => {})
            //这里的tableData是你table上面绑定的list
          },
        })
      },
      // 表格的拖拽属性list
      setSorts() {
        //ref一定跟table上面的ref一致
        const el = this.$refs.tables.$el.querySelectorAll(
          '.el-table__body-wrapper > table > tbody'
        )[0]
        this.sortable = Sortable.create(el, {
          ghostClass: 'sortable-ghost',
          setData: function (dataTransfer) {
            dataTransfer.setData('Text', '')
          },
          // 监听拖拽事件结束时触发
          onEnd: (evt) => {
            // 拖动行的前一行
            const targetRow = this.tableData2.splice(evt.oldIndex, 1)[0]
            // 拖动行的后一行
            this.tableData2.splice(evt.newIndex, 0, targetRow)
            const arr = []
            this.tableData2.forEach((e, index) => {
              //
              arr.push({
                id: e.id,
                sort: index,
              })
            })
            const sortData = JSON.stringify(arr)
            const params = {
              type_id: this.type_id,
              group_id: this.group_id,
              sort_data: sortData,
            }
            setReportItemSort(params).then(() => {})
            // 这里的tableData是你table上面绑定的list
          },
        })
      },
    },
  }
</script>

<style scoped></style>
